package com.kinon.market.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.kinon.market.R;
import com.kinon.market.adapter.DingdanAdapter;
import com.kinon.market.adapter.DingdandetialAdapter;
import com.kinon.market.entity.DingdanEntity;
import com.kinon.market.entity.OrderdetialEntity;
import com.kinon.market.tools.HttpTools;
import com.kinon.market.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2017-3-28 下午5:38:13
 * @类名：RukudingdanFragment.java
 * @功能: 入库单
 */
public class RukudingdanFragment extends Fragment {
    View iscatview = null;

    PullToRefreshGridView pull_dingdan;
    String token;
    DingdanAdapter dingdanAdapter;
    ArrayList<OrderdetialEntity> dingdandetiallist;
    DingdandetialAdapter dingdandetialAdapter;
    HttpTools toolModel = null;
    /**
     * 没有订单
     */
    private TextView tv_none;
    private int offset = 0;
    private int page = 20;
    /**
     * 商品信息的集合
     */
    private ArrayList<DingdanEntity> dingdanlist;
    /**
     * 入库单详情弹窗
     */
    private OnItemClickListener itemclicke = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position,
                                long id) {
            Detialdialog(dingdanlist.get(position).getId());
        }
    };
    /**
     * 上下拉刷新
     */
    private OnRefreshListener2<GridView> onrefresh = new OnRefreshListener2<GridView>() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
            offset = 0;
            dingdanlist.clear();
            toolModel.getRukuorders(token, page + "", offset + "",
                    new JsonDingdans());
            if (NetWorkUtil.isNetwork(getActivity()) == false) {
                //				MyToast.mytoast(getActivity(), "当前网络不可用");
                Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                pull_dingdan.onRefreshComplete();
                return;
            }

        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
            offset += page;
            toolModel.getRukuorders(token, page + "", offset + "",
                    new JsonDingdans());
            //			setSection();
            //			adapter.notifyDataSetChanged();
            if (NetWorkUtil.isNetwork(getActivity()) == false) {
                Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                pull_dingdan.onRefreshComplete();
                return;
            }
        }

    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_rukudingdan, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        initRes();
    }

    private void initRes() {
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");
        pull_dingdan = (PullToRefreshGridView) getView().findViewById(
                R.id.pull_dingdan);

        pull_dingdan.setMode(Mode.BOTH);
        pull_dingdan.setOnRefreshListener(onrefresh);
        pull_dingdan.setOnItemClickListener(itemclicke);
        tv_none = (TextView) getView().findViewById(R.id.tv_none);

        getDingdaninfo();
    }

    /**
     * 获取入库单列表
     */
    private void getDingdaninfo() {
        if (NetWorkUtil.isNetwork(getActivity()) == false) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        dingdanlist = new ArrayList<DingdanEntity>();

        toolModel = new HttpTools(getActivity());
        toolModel.getRukuorders(token, page + "", offset + "",
                new JsonDingdans());
    }

    /**
     * 入库单详情弹窗
     */
    private void Detialdialog(String id) {
//		final ArrayList<OrderdetialEntity> dingdandetiallist ;
//		final DingdandetialAdapter dingdandetialAdapter;
        final Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        iscatview = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_rukuorderdetial, null);
        final TextView tv_orderno = (TextView) iscatview.findViewById(R.id.tv_bianhao);
        final TextView tv_time = (TextView) iscatview.findViewById(R.id.tv_time);
        final TextView tv_fukuanren = (TextView) iscatview.findViewById(R.id.tv_fukuanren);
        final ListView lv = (ListView) iscatview.findViewById(R.id.lv_shangpin);
        Button btn_wancheng = (Button) iscatview.findViewById(R.id.btn_wancheng);

        dialog.setContentView(iscatview);
        dialog.show();

        dingdandetiallist = new ArrayList<OrderdetialEntity>();
        if (toolModel == null) {
            toolModel = new HttpTools(getActivity());
        }
        toolModel.getRukurderdetial(token, id,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            Log.i("info", "入库单详情----" + response.toString());
                            if (code == true) {
                                JSONObject object = response.getJSONObject("data");
//						String input_user = object.getString("input_user");
                                JSONObject data = object.getJSONObject("pwbill");
                                String input_user = data.getString("input_user");
                                String orderno = data.getString("ref");
                                String time = data.getString("biz_dt");
                                JSONArray array = object.getJSONArray("goods");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject goods = array.getJSONObject(i);
                                    String name = goods.getString("name");
                                    String goods_count = goods.getString("goods_count");
                                    String price = goods.getString("goods_money");
                                    dingdandetiallist.add(new OrderdetialEntity(name, goods_count, price));
                                }
                                tv_orderno.setText(orderno);
                                tv_time.setText(time);
                                tv_fukuanren.setText(input_user);
                                dingdandetialAdapter = new DingdandetialAdapter(getActivity(), dingdandetiallist);
                                lv.setAdapter(dingdandetialAdapter);
                                lv.setDivider(null);
//						Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                                          String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                        Toast.makeText(getActivity(), "网络请求超时", Toast.LENGTH_SHORT).show();
                    }

                });


        btn_wancheng.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();

            }
        });
    }

    private class JsonDingdans extends JsonHttpResponseHandler {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            try {
//				Log.i("info","入库单列表----"+response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    JSONArray data = response.getJSONArray("data");
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject object = data.getJSONObject(i);
                        String id = object.getString("id");
                        String ref = object.getString("ref");
                        String time = object.getString("biz_dt");
                        dingdanlist.add(new DingdanEntity(id, ref, time));
                    }
                    Log.e("info", "-----3");
                    if (dingdanlist.size() == 0) {
                        tv_none.setVisibility(View.VISIBLE);
                    } else {
                        tv_none.setVisibility(View.GONE);
                    }
                    dingdanAdapter = new DingdanAdapter(getActivity(), dingdanlist);
                    pull_dingdan.setAdapter(dingdanAdapter);
                    pull_dingdan.getRefreshableView().setSelection(offset);
                    pull_dingdan.setDividerDrawable(null);
                    //				Utility.setGridViewHeightBasedOnChildren(pull_twosort);
                    pull_dingdan.onRefreshComplete();
                } else {
//					pull_dingdan.onRefreshComplete();
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Toast.makeText(getActivity(), "网络请求超时", Toast.LENGTH_SHORT).show();
        }

    }


}
